// 文件上传配置接口
export interface FileUploadConfig {
  accept?: string; // 接受的文件类型，如 "image" 或 "all"
  maxSize?: number; // 最大文件大小（MB）
  maxCount?: number; // 最大文件数量
  uploadUrl?: string; // 上传接口地址
  listType?: "text" | "picture" | "picture-card"; // 显示类型
  tips?: string; // 上传提示信息
}

// 选项数据接口
export interface OptionItem {
  value: string;
  text: string;
}

// 表单字段配置接口
export interface FieldConfig {
  key: string;
  label: string;
  type: "input" | "textarea" | "picker" | "datetime" | "date" | "native-date" | "image-upload" | "file-upload" | "attachment-upload" | "readonly" | "department-picker" | "text" | "autocomplete";
  placeholder: string;
  required?: boolean;
  inputType?: string;
  maxlength?: number;
  pattern?: string; // 正则表达式验证
  patternErrorMessage?: string; // 正则验证失败的错误信息
  options?: string[];
  optionsData?: OptionItem[]; // 选项数据
  fileConfig?: FileUploadConfig; // 文件上传配置
  readonly?: boolean; // 只读字段标识
  showInCreate?: boolean; // 是否在新增页面显示
  showInEdit?: boolean; // 是否在编辑页面显示
  showInDetails?: boolean; // 是否在详情页面显示
  popupTitle?: string; // 弹窗标题（用于department-picker类型）
  departmentData?: any[]; // 部门数据（用于department-picker类型）
  // 自动补全相关配置
  searchApi?: (query: string) => Promise<OptionItem[]>; // 自动补全搜索API
  minSearchLength?: number; // 最小搜索长度
  debounceTime?: number; // 防抖时间
  // 原生日期选择器相关属性
  startDate?: string; // 开始日期
  endDate?: string; // 结束日期
  dateFormat?: 'YYYY-MM-DD' | 'YYYY/MM/DD' | 'MM/DD/YYYY'; // 日期格式
  disabled?: boolean; // 是否禁用
  validation?: (
    value: any,
    formData?: any,
  ) => { valid: boolean; message: string } | true;
}

// 表单分组接口
export interface FormSection {
  key: string;
  title: string;
  fields: FieldConfig[];
}

// 入职申请单表单配置
export const onboardingFormConfig: Record<string, FieldConfig> = {
  // 单据信息
  billCode: {
    key: "billCode",
    label: "单据编号",
    type: "readonly",
    placeholder: "系统自动生成",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  billStatus: {
    key: "billStatus",
    label: "单据状态",
    type: "readonly",
    placeholder: "系统自动生成",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  workflowStatus: {
    key: "workflowStatus",
    label: "工作流状态",
    type: "readonly",
    placeholder: "工作流状态",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  remark: {
    key: "remark",
    label: "备注",
    type: "textarea",
    placeholder: "请输入备注信息",
    required: false,
    maxlength: 200,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 工作信息
  orgId: {
    key: "orgId",
    label: "人事组织",
    type: "department-picker",
    placeholder: "请选择人事组织",
    popupTitle: "选择组织",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: false,
    departmentData: [], // 组织数据，将在页面加载时动态填充
  },
  org: {
    key: "org",
    label: "人事组织",
    type: "readonly",
    placeholder: "人事组织",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  groupId: {
    key: "groupId",
    label: "所属部门",
    type: "department-picker",
    placeholder: "请选择所属部门",
    popupTitle: "选择部门",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: false,
    departmentData: [], // 部门数据，将在页面加载时动态填充
  },
  group: {
    key: "group",
    label: "所属部门",
    type: "readonly",
    placeholder: "所属部门",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  jobPositionId: {
    key: "jobPositionId",
    label: "工作岗位",
    type: "picker",
    placeholder: "请选择工作岗位",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: false,
    options: [], // 岗位选项，将在页面加载时动态填充
    optionsData: [], // 岗位数据，将在页面加载时动态填充
    disabled: false, // 禁用状态，将根据部门选择动态设置
  },
  jobPosition: {
    key: "jobPosition",
    label: "工作岗位",
    type: "readonly",
    placeholder: "工作岗位",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  resumeId: {
    key: "resumeId",
    label: "简历",
    type: "attachment-upload",
    placeholder: "请上传简历",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    fileConfig: {
      accept: "all", // 支持所有文件类型
      maxSize: 10,
      maxCount: 1, // 限制为单文件上传
      listType: "text",
      tips: "支持上传各种格式文件，单个文件不超过10MB"
    },
  },
  joinWorkDate: {
    key: "joinWorkDate",
    label: "参加工作日期",
    type: "native-date",
    placeholder: "请选择参加工作日期",
    required: false,
    showInCreate: false,
    showInEdit: true,
    showInDetails: true,
    startDate: "1950-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },
  hireDate: {
    key: "hireDate",
    label: "入职日期",
    type: "native-date",
    placeholder: "请选择入职日期",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "1950-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },
  employmentType: {
    key: "employmentType",
    label: "用工形式",
    type: "picker",
    placeholder: "请选择用工形式",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: [
      "全职",
      "兼职",
      "实习",
      "外包"
    ],
  },
  contractType: {
    key: "contractType",
    label: "劳动合同类型",
    type: "picker",
    placeholder: "请选择劳动合同类型",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: [
      "固定期限",
      "无固定期限",
      "项目合同"
    ],
  },
  contractNo: {
    key: "contractNo",
    label: "合同编号",
    type: "input",
    placeholder: "请输入合同编号",
    required: false,
    maxlength: 50,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  contractStartDate: {
    key: "contractStartDate",
    label: "合同起始日",
    type: "native-date",
    placeholder: "请选择合同起始日",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "1950-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },
  contractEndDate: {
    key: "contractEndDate",
    label: "合同终止日",
    type: "native-date",
    placeholder: "请选择合同终止日",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "1950-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },

  // 详情页面专用字段
  approver: {
    key: "approver",
    label: "审批人",
    type: "readonly",
    placeholder: "审批人",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  approvalTime: {
    key: "approvalTime",
    label: "审批时间",
    type: "readonly",
    placeholder: "审批时间",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },

  // 员工基本信息字段（用于列表页和详情页）
  name: {
    key: "name",
    label: "姓名",
    type: "readonly",
    placeholder: "姓名",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  staffNo: {
    key: "staffNo",
    label: "工号",
    type: "readonly",
    placeholder: "工号",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  phone: {
    key: "phone",
    label: "手机号",
    type: "readonly",
    placeholder: "手机号",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  gender: {
    key: "gender",
    label: "性别",
    type: "readonly",
    placeholder: "性别",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  idCardNo: {
    key: "idCardNo",
    label: "身份证号",
    type: "readonly",
    placeholder: "身份证号",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
};

// 表单分组配置
export const formSections: FormSection[] = [
  {
    key: "billInfo",
    title: "单据信息",
    fields: [
      onboardingFormConfig.billCode,
      onboardingFormConfig.billStatus,
      onboardingFormConfig.workflowStatus,
      onboardingFormConfig.remark,
    ],
  },
  {
    key: "workInfo",
    title: "工作信息",
    fields: [
      onboardingFormConfig.orgId,
      onboardingFormConfig.org,
      onboardingFormConfig.groupId,
      onboardingFormConfig.group,
      onboardingFormConfig.jobPositionId,
      onboardingFormConfig.jobPosition,
      onboardingFormConfig.resumeId,
      onboardingFormConfig.joinWorkDate,
      onboardingFormConfig.hireDate,
      onboardingFormConfig.employmentType,
      onboardingFormConfig.contractType,
      onboardingFormConfig.contractNo,
      onboardingFormConfig.contractStartDate,
      onboardingFormConfig.contractEndDate,
    ],
  },
  {
    key: "workflowInfo",
    title: "流程信息",
    fields: [
      onboardingFormConfig.approver,
      onboardingFormConfig.approvalTime,
    ],
  },
];

// 根据页面类型过滤表单分组
export const getFormSectionsByPageType = (pageType: 'create' | 'edit' | 'details'): FormSection[] => {
  return formSections.map(section => ({
    ...section,
    fields: section.fields.filter(field => {
      if (pageType === 'create') {
        return field.showInCreate !== false;
      } else if (pageType === 'edit') {
        return field.showInEdit !== false;
      } else if (pageType === 'details') {
        // 详情页根据showInDetails配置显示字段
        return field.showInDetails !== false;
      }
      return false;
    })
  })).filter(section => section.fields.length > 0);
};

// 表单验证函数
export const validateForm = (
  formData: Record<string, any>,
): { valid: boolean; errors: Record<string, string> } => {
  const errors: Record<string, string> = {};
  let valid = true;

  // 遍历所有字段配置
  Object.values(onboardingFormConfig).forEach((field) => {
    const value = formData[field.key];

    // 必填字段验证
    if (field.required && !value) {
      errors[field.key] = `请输入${field.label}`;
      valid = false;
      return;
    }

    // 正则表达式验证
    if (field.pattern && value) {
      const pattern = new RegExp(field.pattern);
      if (!pattern.test(value)) {
        errors[field.key] =
          field.patternErrorMessage || `${field.label}格式不正确`;
        valid = false;
        return;
      }
    }

    // 自定义验证
    if (field.validation && value !== undefined) {
      const result = field.validation(value, formData);
      if (result !== true) {
        errors[field.key] = result.message;
        valid = false;
        return;
      }
    }
  });

  return { valid, errors };
};
